from redis import Redis
from json import loads, dumps

class Cache:

    def __init__(self, host='redis.moth.com', port=6379, **kwargs):
        self.rds = Redis(host=host, port=port, decode_responses=True)

    def __getattr__(self, name):
        if name in self.__dict__:
            return self.__dict__[name]
        return getattr(self.rds, name)

    def delete(self, *names):
        names = [x for x in names if x]
        if names:
            return self.rds.delete(*names)
        return None

    def exists(self, *names):
        names = [x for x in names if x]
        if names:
            return self.rds.exists(*names)
        return None

    def cloads(self, data):
        try:
            return loads(data)
        except:
            return data

    def cdumps(self, data):
        try:
            return dumps(data)
        except:
            return data

    def get(self, name):
        return self.cloads(self.rds.get(name))

    def set(self, name, value, ex=None):
        return self.rds.set(name, self.cdumps(value), ex)

    def hget(self, name, key):
        return self.cloads(self.rds.hget(name, key))

    def hset(self, name, key, value):
        return self.rds.hset(name, key, self.cdumps(value))

    def rpush(self, name, *values):
        return self.rds.rpush(name, *[self.cdumps(x) for x in values])

    def lpush(self, name, *values):
        return self.rds.lpush(name, *[self.cdumps(x) for x in values])

    def lpop(self, name):
        return self.cloads(self.rds.lpop(name))

    def lrange(self, name, start, end):
        data = self.rds.lrange(name, start, end)
        return [self.cloads(x) for x in data]

